using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Cam;
using net_work.Data.Entity.Cam;
using net_work.Data.Enum.Cam;
using net_work.Data.VO.Cam;
using net_work.IRepository.Cam;
using net_work.IRepository.Sys;
using net_work.IService.Cam;

namespace net_work.Service.Cam;

public class MessageService(
    IMessageRepository messageRepository,
    IUserRepository userRepository,
    IDepartmentRepository departmentRepository,
    IAdministrativeClassRepository administrativeClassRepository)
    : IMessageService
{
    public Task<PagedResult<MessageResult>> GetMessagesPagedAsync(PagedRequest request)
    {
        return messageRepository.GetMessagePagedAsync(request);
    }

    public Task<Message?> SelectByIdAsync(long messageId)
    {
        return messageRepository.GetByIdAsync(messageId);
    }

    public async Task<long> InsertMessage(MessageAddRequest messageAddRequest)
    {
        if (messageAddRequest.Type != MessageType.Notice)
        {
            if (messageAddRequest.ObjType != null || messageAddRequest.ObjId != null)
            {
                return -1;
            }
            
            return await messageRepository.InsertAsync(messageAddRequest);
        }

        if (messageAddRequest.ObjType == null || messageAddRequest.ObjId == null)
        {
            return -1;
        }

        switch (messageAddRequest.ObjType)
        {
            case MessageObjType.Dept:
                var department = await departmentRepository.GetByIdAsync(messageAddRequest.ObjId.Value);
                if (department == null)
                {
                    return -1;
                }

                break;
            case MessageObjType.User:
                var user = await userRepository.GetByIdAsync(messageAddRequest.ObjId.Value);
                if (user == null)
                {
                    return -1;
                }

                break;
            case MessageObjType.Class:
                var administrativeClass =
                    await administrativeClassRepository.GetByIdAsync(messageAddRequest.ObjId.Value);
                if (administrativeClass == null)
                {
                    return -1;
                }

                break;
            default:
                throw new ArgumentOutOfRangeException($"{nameof(MessageObjType)}:{messageAddRequest.ObjType}");
        }

        return await messageRepository.InsertAsync(messageAddRequest);
    }

    public async Task<int> UpdateMessage(List<long> messageIds)
    {
        if (!await messageRepository.ValidateByList(messageIds))
        {
            return -1;
        }

        return await messageRepository.UpdateAsync(messageIds) ? 1 : -1;
    }

    public async Task<int> DeleteMessageByIds(List<long> ids)
    {
        return await messageRepository.DeleteByIdsAsync(ids) ? 1 : -1;
    }
}